<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Right Click Context Menu</title>
    <style>
        #context-menu {
            position: absolute;
            background-color: #f9f9f9;
            border: 1px solid #ccc;
            box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.3);
            padding: 5px;
            z-index: 1000;
        }

        #context-menu ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
        }

        #context-menu li {
            padding: 5px;
        }

        #context-menu li:hover {
            background-color: #e9e9e9;
        }

        .hidden {
            display: none;
        }
    </style>
</head>
<body>
<div id="content">
    <p>右键点击这里显示上下文菜单。</p>
</div>
<div id="context-menu" class="hidden">
    <ul>
        <li><a href="#" onclick="alert('复制')">复制</a></li>
        <li><a href="#" onclick="alert('粘贴')">粘贴</a></li>
        <li><a href="#" onclick="alert('删除')">删除</a></li>
    </ul>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const contextMenu = document.getElementById('context-menu');

        function showContextMenu(event) {
            event.preventDefault(); // 阻止浏览器默认的行为（打开上下文菜单）

            // 计算菜单的位置
            const x = event.clientX;
            const y = event.clientY;

            // 显示上下文菜单
            contextMenu.style.top = y + 'px';
            contextMenu.style.left = x + 'px';
            contextMenu.classList.remove('hidden');
        }

        function hideContextMenu() {
            contextMenu.classList.add('hidden');
        }

        // 添加右键点击事件监听器
        document.getElementById('content').addEventListener('contextmenu', showContextMenu);

        // 添加点击文档其他地方隐藏菜单的事件监听器
        document.addEventListener('click', function (event) {
            if (event.target !== contextMenu && !contextMenu.contains(event.target)) {
                hideContextMenu();
            }
        });

        // 添加键盘事件监听器，按 ESC 键隐藏菜单
        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape') {
                hideContextMenu();
            }
        });
    });
</script>
</body>
</html>